package com.wind.plugin.configuration;

import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.ArrayList;

/**
 * @author wind
 * @version 1.0
 * @description: TODO
 * @date 2025/2/15 15:38
 */
public class PluginSettingsConfigurable implements Configurable {
    private PluginSettingsComponent settingsComponent;

    @Nls(capitalization = Nls.Capitalization.Title)
    @Override
    public String getDisplayName() {
        return "GuardDev Settings";
    }

    @Override
    public @Nullable JComponent createComponent() {
        if (settingsComponent == null) {
            settingsComponent = new PluginSettingsComponent();
        }
        return settingsComponent.getPanel();
    }

    // 修改isModified和apply方法
    @Override
    public boolean isModified() {
        PluginSettingsState settings = PluginSettingsState.getInstance();
        return !settingsComponent.getClassPanel().getHighlightClasses().equals(settings.getHighlightClasses()) ||
                !settingsComponent.getFieldPanel().getHighlightFields().equals(settings.getCurrencyFields());
    }

    @Override
    public void apply() {
        PluginSettingsState settings = PluginSettingsState.getInstance();
        settings.setHighlightClasses(settingsComponent.getClassPanel().getHighlightClasses());
        settings.setCurrencyFields(settingsComponent.getFieldPanel().getHighlightFields());
        // 改为遍历所有打开的项目
        for (Project project : ProjectManager.getInstance().getOpenProjects()) {
            DaemonCodeAnalyzer.getInstance(project).restart();
        }
    }

    @Override
    public void reset() {
        PluginSettingsState settings = PluginSettingsState.getInstance();
        settingsComponent.getClassPanel().setHighlightClasses(new ArrayList<>(settings.getHighlightClasses()));
        settingsComponent.getFieldPanel().setFieldList(new ArrayList<>(settings.getCurrencyFields()));
    }

    @Override
    public void disposeUIResources() {
        this.settingsComponent = null;
    }
}


